import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']

def pltInit(x,y,xlabel,ylabel,title):
    plt.figure(figsize=(16, 9))
    plt.title(title)
    plt.bar(x, y)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

# 查看用户收听音乐个歌手所占比重
def perferAuthorProp(data):
    author = {}
    for i in data["Author"]:
        if i in author:
            author[i]+=1
        else:
            author[i]=1
    author["其他歌手"] = 0
    for i in list(author.keys()):
        if author[i]<3:
            author["其他歌手"]+=author[i]
            author.pop(i)
    plt.title("歌手喜好比重")
    plt.pie(author.values(),labels=author.keys(),autopct="%.1f%%")
    plt.show()

# 查看用户收听音乐中分类所占比重
def perferTypeProp(data):
    types = {}
    for i in data["Type"]:
        if i in types:
            types[i]+=1
        else:
            types[i]=1
    plt.title("音乐类型喜好比重")
    plt.pie(types.values(),labels=types.keys(),autopct="%.1f%%")
    plt.show()

# 查看用户收听音乐次数的频数直方图
def perferByFrequency(data):
    height = np.array(data["Time"])
    bins = range(0,200,10)
    plt.figure(figsize=(16,9))
    plt.title("收听次数频数分布直方图")
    plt.xlabel("收听次数")
    plt.ylabel("频数")
    plt.hist(height,bins=bins)
    plt.show()

# 查看用户收听次数最多的十首歌曲
def perferByTime(data):
    # Top10 = data.loc[data["Id"]<=10]
    # pltInit(Top10["Name"],Top10["Time"],"歌曲名称","收听次数","喜好音乐Top10")
    # plt.xticks(rotation=10)
    # plt.show()
    Top5 = data.loc[data["Id"] <= 5]
    pltInit(Top5["Name"],Top5["Time"],"歌曲名称","收听次数","喜好音乐Top5")
    plt.xticks(rotation=10)
    plt.show()

# 查看用户对不同歌手的音乐收听情况
def perferAuthorTime(data):
    author = {}
    for i in data["Author"]:
        if i not in author:
            author[i] = 0
    for i in range(1,100):
        author[data.loc[data["Id"]==i].iat[0,2]]+=data.loc[data["Id"]==i].iat[0,3]
    pltInit(author.keys(),author.values(),"歌手","收听总次数","各歌手收听情况汇总")
    plt.xticks(rotation=15)
    plt.show()




# 查看用户对某个歌手的音乐收听情况
def perferByAuthor(data,author):
    x = np.array(data.loc[data["Author"] == author]["Name"])
    y = np.array(data.loc[data["Author"] == author]["Time"])
    pltInit(x, y, "歌曲名称", "收听次数", "用户对于" + author + "的喜好情况")
    plt.show()



data = pd.read_csv("./music.csv",encoding="gbk")
# perferByAuthor(data,"鹿乃")
perferByAuthor(data,"薛之谦")
perferTypeProp(data)
perferByFrequency(data)
perferByTime(data)
perferAuthorProp(data)
perferAuthorTime(data)